package com.nsi.async;

import com.nsi.pojo.Order;
import com.nsi.service.IOrderService;
import com.nsi.util.MailUtil;
import com.nsi.util.PropertiesUtil;
import com.nsi.util.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;

/**
 * 异步发送消息
 *
 * @author Luo Zhen
 * @create 2019-08-29 10:40
 */
@Component
@Slf4j
public class AsyncTask {

    @Autowired
    private SmsUtil smsUtil;
    @Autowired
    private IOrderService iOrderService;

    /**
     * 发送报名成功,未付费的信息
     *
     * @param telphone
     * @param activeName
     */
    @Async
    public void sendNoPayMessage(String telphone, String activeName) {
        try {
            // 间隔60秒发送短信
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("==========[异步发送未付款短信]==========");
        //验证订单是否支付
        Order order = iOrderService.findOrderstatusBywechatId(telphone);
        if (order == null) {
            // 发送短信通知
            String nopayCode = PropertiesUtil.getProperty("sms.noPay.code");
            String params = "{\"name\":\"" + activeName + "\"}";
            smsUtil.sendSms(telphone, nopayCode, params);
        }
        return;
    }

    /**
     * 发送付费成功短信
     *
     * @param telphone
     * @param activeName
     */
    @Async
    public void sendPayMessage(String telphone, String activeName) {
        log.info("【异步发送已付款短信】");
        String params = "{\"name\":\"" + activeName + "\"}";
        String payCode = PropertiesUtil.getProperty("sms.pay.code");
        smsUtil.sendSms(telphone, payCode, params);
    }

    @Async
    public void sendAdminEmail(String message) {
        log.info("【异步发送已付费信息给管理员邮箱】");
        String adminEmail = PropertiesUtil.getProperty("admin.email");
        try {
            MailUtil.SendNotifyMail(adminEmail, message);
        } catch (Exception e) {
            log.error("【发送管理员邮箱失败】msg:{}", e.getMessage());
        }
    }

    @Async
    public void sendRegisterCode(String toWho, String code) {
        log.info("【异步发送邮箱注册码】");
        try {
            MailUtil.sendMailRegisterCode(toWho, code);
        } catch (MessagingException e) {
            log.error("【发送邮箱注册码】msg:{}", e.getMessage());
        } catch (Exception e) {
            log.error("【发送邮箱注册码】msg:{}", e.getMessage());
        }
    }
}
